//
//  EditAddressController.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/7/5.
//

import UIKit

class EditAddressController: ZsBaseViewController,UITextFieldDelegate {

    var addressType:Int!
    var addressModel:AddressModel!
    @IBOutlet weak var addressListBtn: UIButton!
    @IBOutlet weak var bottomViewHeight: NSLayoutConstraint!
    @IBOutlet weak var countryBtn: UIButton!
    @IBOutlet weak var addressBtn: UIButton!

    @IBOutlet weak var phoneTF: UITextField!
    @IBOutlet weak var nameTF: UITextField!
    @IBOutlet weak var addressTF: UITextField!
    @IBOutlet weak var detailAddressTF: UITextField!

    @IBOutlet weak var saveBtn: UIButton!
    @IBOutlet weak var clearBtn: UIButton!
    @IBOutlet weak var contactsLab: UILabel!
    @IBOutlet weak var selectBtn: UIButton!
    @IBOutlet weak var hintLab: UILabel!
    @IBOutlet weak var setDefaultView: UIView!
    @IBOutlet weak var oneLineView: UIView!
    @IBOutlet weak var mainView: UIView!
    
    var nameStr:String = ""
    var phoneStr:String = ""
    var countryCodeModel:WLCountryCode!
    var selectCityModel:WLCityModel!

    typealias AddressListBlock = (_ userAddressModel:AddressModel,_ index:Int) -> Void
    var selectAddressBlock : AddressListBlock!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if addressType == 1 {
            self.title = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.editSender_contacts)
        } else if addressType == 2 {
            self.title = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.editRecrive_contacts)
        } else if addressType == 0 && addressModel.id.count > 0{
            self.title = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_edit_contacts)
        } else {
            self.title = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_add_contacts)
        }
        self.view.backgroundColor = UIColor.init(hexString: "#F3F3F3")
        let ary = CacheTool.cacheTool.getCommonAreas()
        if ary.count > 1 {
            countryCodeModel = ary[1]
            countryBtn.setTitle(countryCodeModel.phonecode, for: .normal)
        }
        phoneTF.placeholder = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.hint_import_TEL)
        nameTF.placeholder = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_realName)
        addressTF.placeholder = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_cityAndarea)
        detailAddressTF.placeholder = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_detailAddress)
        clearBtn.setTitle(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_clear_data), for: .normal)
        contactsLab.text = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_address_contacts)
        saveBtn.setTitle(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_save), for: .normal)
        hintLab.text = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_set_defaultAddress)
        addressListBtn.setTitle(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_lookExpress), for: .normal)
        saveBtn.layer.cornerRadius = 20
        addressTF.isUserInteractionEnabled = false
        if addressType != 0 {
            addressListBtn.isHidden = true
            setDefaultView.isHidden = true
        } else {
            addressListBtn.isHidden = false
            setDefaultView.isHidden = false
        }
        nameTF.delegate = self
        phoneTF.delegate = self
        detailAddressTF.delegate = self
        addressTF.delegate = self
        nameTF.autocorrectionType = UITextAutocorrectionType.no
        mainView.layer.shadowColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.2).cgColor
        mainView.layer.shadowOffset = CGSize.init(width: 0, height: 1)
        mainView.layer.shadowOpacity = 1
        mainView.layer.shadowRadius = 2
        mainView.layer.cornerRadius = 5
        bottomViewHeight.constant = 56 + Constants.xSafeBottomHeight
        self.setAddressModel(addressModel: addressModel)
        self.nameTF.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
    }
    
    func setAddressModel(addressModel:AddressModel) {
        self.addressModel = addressModel
        if addressModel.name.count > 0 {
            self.selectCityModel.id = addressModel.regionId
            self.selectCityModel.name = addressModel.region
            selectCityModel.parentID = addressModel.cityId
            selectCityModel.parentName = addressModel.city
            
            addressTF.text = addressModel.city + addressModel.region
            phoneTF.text = addressModel.phone
            nameTF.text = addressModel.name
            nameStr = addressModel.name
            phoneStr = addressModel.phone
            detailAddressTF.text = addressModel.detailAddress
            saveBtn.backgroundColor = UIColor.init(hexString: "#FFD10A")
            selectBtn.isSelected = addressModel.isDefault == 0 ? false : true
        } else {
            saveBtn.backgroundColor = UIColor.init(hexString: "#E3E3E3")
        }
    }
    @IBAction func selectcountry(_ sender: UIButton) {
        self.view.endEditing(true)
        Constants.window?.addSubview(self.selectCountryView)
    }
    @IBAction func selectAddressBtn(_ sender: UIButton) {
        self.view.endEditing(true)
        Constants.window?.addSubview(self.selectAddressView)
    }
    @IBAction func clearData(_ sender: UIButton) {
        self.view.endEditing(true)
        nameTF.text = ""
        phoneTF.text = ""
        addressTF.text = ""
        nameStr = ""
        phoneStr = ""
        detailAddressTF.text = ""
    }
    @IBAction func clickAddressListBtn(_ sender: UIButton) {
        let AddressListC = AddressListController.init()
        AddressListC.setIndex(index: addressType)
        AddressListC.selectAddressBlock = { (userAddressModel,index) in
            self.addressModel = userAddressModel
        }
        self.navigationController?.pushViewController(AddressListC, animated: true)
    }
    @IBAction func clickAddressSelectBtn(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if addressModel.id.count > 0 {
            if sender.isSelected {
                Constants.window?.makeToastActivity(.center)
                HttpService.sharedHttpService().setDefaultAddress(ID: addressModel.id) { (jaon, state, error) in
                    Constants.window?.hideToastActivity()
                    if state {
                        self.addressModel.isDefault = 1
                    } else {
                        Constants.window?.makeToast(error)
                    }
                }
            } else {
                Constants.window?.makeToastActivity(.center)
                HttpService.sharedHttpService().cancelDefaultAddress(ID: addressModel.id) { (json, state, error) in
                    Constants.window?.hideToastActivity()
                    if state {
                        self.addressModel.isDefault = 0
                    } else {
                        Constants.window?.makeToast(error)
                    }
                }
            }
        }
    }
    @IBAction func clickSaveBtn(_ sender: UIButton) {
        if nameTF.text?.count ?? 0 < 0 {
            Constants.window?.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_hint_name_not))
            return
        } else if (phoneTF.text?.count ?? 0 <= 0) {
            Constants.window?.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_hint_phone_not))
            return
        } else if (addressTF.text?.count ?? 0 <= 0) {
            Constants.window?.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_hint_city_not))
            return
        } else if (detailAddressTF.text?.count ?? 0 <= 0) {
            Constants.window?.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_hint_address_not))
            return
        }
        if addressModel.id.count > 0 && phoneTF.text == addressModel.phone && selectBtn.isSelected == (addressModel.isDefault == 0 ? false : true) && nameTF.text == addressModel.name && selectCityModel.parentID == addressModel.cityId && selectCityModel.parentName == addressModel.city && selectCityModel.name == addressModel.region && selectCityModel.id == addressModel.regionId {
            if (selectAddressBlock != nil) {
                selectAddressBlock(addressModel,addressType)
            }
            self.navigationController?.popViewController(animated: true)
            return
        }
        if selectCityModel.name.count > 0 {
            var dicData = ["phone":phoneTF.text ?? "","isDefault":selectBtn.isSelected ? 1 : 0,"city":selectCityModel.parentName,"regionId":selectCityModel.id,"name":nameTF.text ?? "","detailAddress":detailAddressTF.text ?? "","cityId":selectCityModel.parentID,"region":selectCityModel.name,"userId":WLUserModel.getEmail(),"phoneCode":countryCodeModel.phonecode] as [String : Any]
            
            if addressModel.id.count > 0 {
                dicData["id"] = addressModel.id
                HttpService.sharedHttpService().modifyAddress(dicData: dicData) { (model, state, error) in
                    Constants.window?.hideToastActivity()
                    if state {
                        if self.addressType == 0 {
                            if (self.selectAddressBlock != nil) {
                                self.selectAddressBlock(model,self.addressType)
                            }
                            self.navigationController?.popViewController(animated: true)
                        } else {
                            self.addressModel = model
                            self.judgesuperzone()
                        }
                    } else {
                        Constants.window?.makeToast(error)
                    }
                }
            } else {
                HttpService.sharedHttpService().addAddress(dicData: dicData) { (model, state, error) in
                    Constants.window?.hideToastActivity()
                    if state {
                        if self.addressType == 0 {
                            if (self.selectAddressBlock != nil) {
                                self.selectAddressBlock(model,self.addressType)
                            }
                            self.navigationController?.popViewController(animated: true)
                        } else {
                            self.addressModel = model
                            self.judgesuperzone()
                        }
                    } else {
                        Constants.window?.makeToast(error)
                    }
                }
            }
        }
    }
    func judgesuperzone()  {
        let dicData:Dictionary = ["cityId":addressModel.cityId,"cityName":addressModel.city,"operateType":addressType ?? "","regionId":addressModel.regionId,"regionName":addressModel.region] as [String : Any]
        HttpService.sharedHttpService().getrecAndSendSupport(dicData: dicData) { (json, state, error) in
            Constants.window?.hideAllToasts()
            if state {
                if json["code"].int == 302 {
                    Constants.window?.makeToast(json["message"].description)
                    self.addressModel.supportDelivery = true
                } else {
                    self.addressModel.supportDelivery = false
                }
                if (self.selectAddressBlock != nil) {
                    self.selectAddressBlock(self.addressModel,self.addressType)
                    self.navigationController?.popViewController(animated: true)
                }
            } else {
                Constants.window?.makeToast(error)
            }
        }
        
    }
    
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        if nameTF == textField {
            nameStr = ""
        } else if phoneTF == textField {
            phoneStr = ""
        }
        return true
    }
    
    @objc func textFieldDidChange() {
        if phoneTF.text?.count ?? 0 > 0 && phoneTF.text?.count ?? 0 > 0 && detailAddressTF.text?.count ?? 0 > 0 && addressTF.text?.count ?? 0 > 0 {
            saveBtn.backgroundColor = UIColor.init(hexString: "#FFD10A")
        } else {
            saveBtn.backgroundColor = UIColor.init(hexString: "#E3E3E3")
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.view.endEditing(true)
    }
    lazy var selectCountryView: SelectCountryView = {
        let selectCountryView = SelectCountryView.init(frame: CGRect.init(x: 0, y: 0, width: Constants.screenWidth, height: Constants.screenHeight))
        selectCountryView.selectCountryViewBlock = { countryCodeModel in
            self.countryCodeModel = countryCodeModel
            self.countryBtn.setTitle(countryCodeModel.phonecode, for: .normal)
        }
        selectCountryView.refreshData()
        return selectCountryView
    }()
    lazy var selectAddressView: SelectAddressView = {
        let selectAddressView = SelectAddressView.init(frame: CGRect.init(x: 0, y: 0, width: Constants.screenWidth, height: Constants.screenHeight))
        selectAddressView.selectAddressBlock = { selectCityModel in
            self.selectCityModel = selectCityModel
            self.addressTF.text = selectCityModel.parentName + selectCityModel.name
        }
        return selectAddressView
    }()

}
